<template>
  <div class="book-container">
    <h1 class="page-title">图书管理</h1>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form inline="true" size="small" class="search-form">
        <el-form-item label="图书编号">
          <el-input v-model="search1" placeholder="请输入图书编号" clearable>
            <template #prefix><el-icon class="form-icon"><search /></el-icon></template>
          </el-input>
        </el-form-item>
        <el-form-item label="图书名称">
          <el-input v-model="search2" placeholder="请输入图书名称" clearable>
            <template #prefix><el-icon class="form-icon"><search /></el-icon></template>
          </el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="search3" placeholder="请输入作者" clearable>
            <template #prefix><el-icon class="form-icon"><search /></el-icon></template>
          </el-input>
        </el-form-item>
        <div class="search-buttons">
          <el-button type="primary" @click="load" class="search-button">
            <span>查询</span>
          </el-button>
          <el-button type="info" @click="clear" class="reset-button">
            <span>重置</span>
          </el-button>
        </div>
        <el-form-item class="overdue-notice" v-if="numOfOutDataBook!=0">
          <el-popconfirm
              confirm-button-text="查看"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="red"
              title="您有图书已逾期，请尽快归还"
              @confirm="toLook"
          >
            <template #reference>
              <el-button type="warning" class="warning-button">
                <span>逾期通知</span>
              </el-button>
            </template>
          </el-popconfirm>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="add" v-if="user.role == 1">
        <span>上架新书</span>
      </el-button>
      <el-popconfirm title="确认批量删除这些图书吗?" @confirm="deleteBatch" v-if="user.role == 1">
        <template #reference>
          <el-button type="danger">
            <span>批量删除</span>
          </el-button>
        </template>
      </el-popconfirm>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="tableData" 
      stripe 
      border="true" 
      @selection-change="handleSelectionChange"
      class="book-table"
      highlight-current-row
      v-loading="loading"
    >
      <el-table-column v-if="user.role == 1"
                       type="selection"
                       width="55">
      </el-table-column>
      <el-table-column prop="isbn" label="图书编号" sortable />
      <el-table-column prop="name" label="图书名称" />
      <el-table-column prop="price" label="价格" sortable />
      <el-table-column prop="author" label="作者" />
      <el-table-column prop="publisher" label="出版社" />
      <el-table-column prop="createTime" label="出版时间" sortable />
      <el-table-column prop="status" label="状态">
        <template v-slot="scope">
          <el-tag v-if="scope.row.status == 0" type="warning">已借阅</el-tag>
          <el-tag v-else type="success">未借阅</el-tag>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="220">
        <template v-slot="scope">
          <div class="table-actions">
            <el-button type="primary" size="small" plain @click="handleEdit(scope.row)" v-if="user.role == 1">
              <span>修改</span>
            </el-button>
            <el-popconfirm title="确认删除此图书?" @confirm="handleDelete(scope.row.id)" v-if="user.role == 1">
              <template #reference>
                <el-button type="danger" size="small" plain>
                  <span>删除</span>
                </el-button>
              </template>
            </el-popconfirm>
            <el-button type="success" size="small" plain @click="handlelend(scope.row.id,scope.row.isbn,scope.row.name,scope.row.borrownum)" v-if="user.role == 2" :disabled="scope.row.status == 0">
              <span>借阅</span>
            </el-button>
            <el-popconfirm title="确认归还此书?" @confirm="handlereturn(scope.row.id,scope.row.isbn,scope.row.borrownum)" v-if="user.role == 2" :disabled="scope.row.status == 1">
              <template #reference>
                <el-button type="warning" size="small" plain :disabled="(isbnArray.indexOf(scope.row.isbn)) == -1 ||scope.row.status == 1">
                  <span>还书</span>
                </el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 逾期通知对话框 -->
    <el-dialog
        v-model="dialogVisible3"
        v-if="numOfOutDataBook!=0"
        title="逾期详情"
        width="50%"
        :before-close="handleClose"
        class="custom-dialog"
    >
        <el-table :data="outDateBook" style="width: 100%" class="overdue-table">
          <el-table-column prop="isbn" label="图书编号" />
          <el-table-column prop="bookName" label="书名" />
          <el-table-column prop="lendtime" label="借阅日期" />
          <el-table-column prop="deadtime" label="截至日期" />
        </el-table>

      <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="dialogVisible3 = false">确认</el-button>
      </span>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:currentPage="currentPage"
          :page-sizes="[5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
      >
      </el-pagination>
    </div>

    <!-- 上架/修改书籍对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="form.id ? '修改书籍信息' : '上架新书'" 
      width="500px"
      class="custom-dialog"
    >
      <el-form :model="form" label-width="100px" class="book-form">
        <el-form-item label="图书编号">
          <el-input v-model="form.isbn" placeholder="请输入图书编号"></el-input>
        </el-form-item>
        <el-form-item label="图书名称">
          <el-input v-model="form.name" placeholder="请输入图书名称"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="form.author" placeholder="请输入作者"></el-input>
        </el-form-item>
        <el-form-item label="出版社">
          <el-input v-model="form.publisher" placeholder="请输入出版社"></el-input>
        </el-form-item>
        <el-form-item label="出版时间">
          <el-date-picker 
            value-format="YYYY-MM-DD" 
            type="date" 
            style="width: 100%" 
            clearable 
            v-model="form.createTime" 
            placeholder="请选择出版日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// @ is an alias to /src
import request from "../utils/request";
import {ElMessage} from "element-plus";
import moment from "moment";
export default {
  created(){
    let userStr = sessionStorage.getItem("user") ||"{}"
    this.user = JSON.parse(userStr)
    this.load()
  },
  name: 'Book',
  methods: {
  // (this.isbnArray.indexOf(scope.row.isbn)) == -1
    handleSelectionChange(val){
      this.ids = val.map(v =>v.id)
    },
    deleteBatch(){
      if (!this.ids.length) {
        ElMessage.warning("请选择数据！")
        return
      }
      //  一个小优化，直接发送这个数组，而不是一个一个的提交删除
      request.post("/book/deleteBatch",this.ids).then(res =>{
        if(res.code === '0'){
          ElMessage.success("批量删除成功")
          this.load()
        }
        else {
          ElMessage.error(res.msg)
        }
      })
    },
    load(){
      this.numOfOutDataBook =0;
      this.outDateBook =[];
      request.get("/book",{
        params:{
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          search1: this.search1,
          search2: this.search2,
          search3: this.search3,
        }
      }).then(res =>{
        console.log(res)
        this.tableData = res.data.records
        this.total = res.data.total
      })
    //
      if(this.user.role == 2){
        request.get("/bookwithuser",{
          params:{
            pageNum: "1",
            pageSize: this.total,
            search1: "",
            search2: "",
            search3: this.user.id,
          }
        }).then(res =>{
          console.log(res)
          this.bookData = res.data.records
          this.number = this.bookData.length;
          var nowDate = new Date();
          for(let i=0; i< this.number; i++){
            this.isbnArray[i] = this.bookData[i].isbn;
            let dDate = new Date(this.bookData[i].deadtime);
            if(dDate < nowDate){
              this.outDateBook[this.numOfOutDataBook] = {
                isbn:this.bookData[i].isbn,
                bookName : this.bookData[i].bookName,
                deadtime : this.bookData[i].deadtime,
                lendtime : this.bookData[i].lendtime,
              };
              this.numOfOutDataBook = this.numOfOutDataBook + 1;
            }
          }
          console.log("in load():" +this.numOfOutDataBook );
        })
      }
      //
    },
    clear(){
      this.search1 = ""
      this.search2 = ""
      this.search3 = ""
      this.load()
    },

    handleDelete(id){
      request.delete("book/" + id ).then(res =>{
        console.log(res)
        if(res.code == 0 ){
          ElMessage.success("删除成功")
        }
        else
          ElMessage.error(res.msg)
        this.load()
      })
    },
    handlereturn(id,isbn,bn){
      // (this.isbnArray.indexOf(scope.row.isbn)) == -1
      // for(let i=0; i<this.numOfOutDataBook; i++){
      //   if(this.outDateBook[i].isbn == isbn){
      //     this.numOfOutDataBook = this.numOfOutDataBook -1;
      //     console.log("in handlereturn: " + this.numOfOutDataBook);
      //     break;
      //   }
      // }
      this.form.status = "1"
      this.form.id = id
      request.put("/book",this.form).then(res =>{
        console.log(res)
        if(res.code == 0){
          ElMessage({
            message: '还书成功',
            type: 'success',
          })
        }
        else {
          ElMessage.error(res.msg)
        }
      //
        this.form3.isbn = isbn
        this.form3.readerId = this.user.id
        let endDate = moment(new Date()).format("yyyy-MM-DD HH:mm:ss")
        this.form3.returnTime = endDate
        this.form3.status = "1"
        console.log(bn)
        this.form3.borrownum = bn
        request.put("/LendRecord1/",this.form3).then(res =>{
          console.log(res)
          let form3 ={};
          form3.isbn = isbn;
          form3.bookName = name;
          form3.nickName = this.user.username;
          form3.id = this.user.id;
          form3.lendtime = endDate;
          form3.deadtime = endDate;
          form3.prolong  = 1;
          request.post("/bookwithuser/deleteRecord",form3).then(res =>{
            console.log(res)
            this.load()
          })

        })
      //
      })
      // this.form3.isbn = isbn
      // this.form3.readerId = this.user.id
      // let endDate = moment(new Date()).format("yyyy-MM-DD HH:mm:ss")
      // this.form3.returnTime = endDate
      // this.form3.status = "1"
      // console.log(bn)
      // this.form3.borrownum = bn
      // request.put("/LendRecord1/",this.form3).then(res =>{
      //   console.log(res)
      // })
      // let form3 ={};
      // form3.isbn = isbn;
      // form3.bookName = name;
      // form3.nickName = this.user.username;
      // form3.id = this.user.id;
      // form3.lendtime = endDate;
      // form3.deadtime = endDate;
      // form3.prolong  = 1;
      // request.post("/bookwithuser/deleteRecord",form3).then(res =>{
      //   console.log(res)
      //   this.load()
      // })
    },
    handlelend(id,isbn,name,bn){
      if(this.number ==5){
        ElMessage.warning("您不能再借阅更多的书籍了")
        return;
      }
      if(this.numOfOutDataBook !=0){
        ElMessage.warning("在您归还逾期书籍前不能再借阅书籍")
        return;
      }
      this.form.status = "0"
      this.form.id = id
      this.form.borrownum = bn+1
      console.log(bn)
      request.put("/book",this.form).then(res =>{
        console.log(res)
        if(res.code == 0){
          ElMessage({
            message: '借阅成功',
            type: 'success',
          })
        }
        else {
          ElMessage.error(res.msg)
        }
      })

      this.form2.status = "0"
      this.form2.isbn = isbn
      this.form2.bookname = name
      this.form2.readerId = this.user.id
      this.form2.borrownum = bn+1
      console.log(this.form2.borrownum)
      console.log(this.user)
      let startDate = moment(new Date()).format("yyyy-MM-DD HH:mm:ss");
      this.form2.lendTime = startDate
      console.log(this.user)
      request.post("/LendRecord",this.form2).then(res =>{
        console.log(res)
        this.load();

      })
      let form3 ={};
      form3.isbn = isbn;
      form3.bookName = name;
      form3.nickName = this.user.username;
      form3.id = this.user.id;
      form3.lendtime = startDate;
      let nowDate = new Date(startDate);
      nowDate.setDate(nowDate.getDate()+30);
      form3.deadtime = moment(nowDate).format("yyyy-MM-DD HH:mm:ss");
      form3.prolong  = 1;
      request.post("/bookwithuser/insertNew",form3).then(res =>{
        console.log(res)
        this.load()
      })
    },
    add(){
      this.dialogVisible= true
      this.form ={}
    },
    save(){
      //ES6语法
      //地址,但是？IP与端口？+请求参数
      // this.form?这是自动保存在form中的，虽然显示时没有使用，但是这个对象中是有它的
      if(this.form.id){
        request.put("/book",this.form).then(res =>{
          console.log(res)
          if(res.code == 0){
            ElMessage({
              message: '修改书籍信息成功',
              type: 'success',
            })
          }
          else {
            ElMessage.error(res.msg)
          }

          this.load()
          this.dialogVisible2 = false
        })
      }
      else {
        this.form.borrownum = 0
        this.form.status = 1
        request.post("/book",this.form).then(res =>{
          console.log(res)
          if(res.code == 0){
            ElMessage.success('上架书籍成功')
          }
          else {
            ElMessage.error(res.msg)
          }
          this.load()
          this.dialogVisible = false
        })
      }

    },
    // formatter(row) {:formatter="formatter"
    //   return row.address
    // },

    handleEdit(row){
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogVisible2 = true
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum){
      this.pageNum = pageNum
      this.load()
    },
    toLook(){
      this.dialogVisible3 =true;
    },
  },
  data() {
    return {
      form: {},
      form2:{},
      form3:{},
      dialogVisible: false,
      dialogVisible2: false,
      search1:'',
      search2:'',
      search3:'',
      total:10,
      currentPage:1,
      pageSize: 10,
      tableData: [],
      user:{},
      number:0,
      bookData:[],
      isbnArray:[],
      outDateBook:[],
      numOfOutDataBook: 0,
      dialogVisible3 : true,
    }
  },
}
</script>

<style scoped>
.book-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: var(--border-radius-medium);
  box-shadow: var(--box-shadow);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: 10px;
}

.search-buttons {
  display: flex;
  gap: 10px;
  margin-left: 10px;
}

.form-icon {
  color: var(--text-secondary);
}

.search-button, .reset-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.warning-button {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-left: auto;
}

.overdue-notice {
  margin-left: auto;
}

.action-buttons {
  margin: 20px 0;
  display: flex;
  gap: 10px;
}

.book-table {
  margin-bottom: 20px;
  border-radius: var(--border-radius-medium);
  overflow: hidden;
}

.table-actions {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
  justify-content: center;
}

.el-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.custom-dialog :deep(.el-dialog__header) {
  background-color: var(--primary-color);
  color: white;
  padding: 15px 20px;
}

.custom-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 30px 20px;
}

.book-form .el-form-item {
  margin-bottom: 20px;
}

.overdue-table {
  margin-bottom: 20px;
}
</style>
